<template>
  <div id="wechatcode">
  </div>
</template>

<script>

  export default{
    name: 'wechatcode',
    components: {
    },
    data () {
      return {
        appid: this.getCookie('appid'),
        wxredirectname: sessionStorage.getItem('wxredirectname') || 'home'
      }
    },
    created: function () {
      this.getObjDetail(this.apidomain + '/api/wechat/mp/getUserInfo/' + this.getCookie('appid'), {
        code: this.getQueryString('code'),
        scope: 'snsapi_userinfo'
      })
      .then((data) => {
        if (data.openid !== undefined) {
          this.setCookie('openid', data.openid)
          localStorage.userInfo = JSON.stringify(data)
          this.setCookie('islogin', 'true')
          setTimeout(() => {
            sessionStorage.removeItem('wxredirectname')
            if (this.wxredirectname.indexOf('appraise') > -1) {
              window.location.href = this.basedomain + '/#/' + this.wxredirectname + '&appid=' + this.appid + '&wxredirectname=appraise'
            } else {
              window.location.href = this.basedomain + '/#/' + this.wxredirectname + '?appid=' + this.appid + '&wxredirectname=' + this.wxredirectname
            }
            // this.routeto(this.wxredirectname)
          }, 200)
        } else {
          window.alert('授权失败！')
          window.WeixinJSBridge.invoke('closeWindow')
        }
      }, () => {})
    },
    methods: {
      getQueryString: function (name) {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        const r = window.location.search.substr(1).match(reg)
        if (r != null) {
          return unescape(r[2])
        } else {
          return ''
        }
      },
      getQueryAll: function (url) {
        if (url.indexOf('?') > -1) {
          const urlarr = url.split('?')
          return urlarr[1]
        } else {
          return ''
        }
      }
    }
  }
</script>
<style>
</style>
